<template>
  <div>
    <NavigationComponent />
    <br />
    <div class="student-list-container">
      <span>{{ class_name }}</span>
      <div v-if="students.length">
        <h3>抽奖列表：</h3>
        <ul>
          <li v-for="(student, index) in students" :key="index" :class="{ 'selected': index === selectedStudentIndex }" class="student-item">
            <img :src="student.image" alt="student image" width="20" height="20" />
            {{ student.name }}
          </li>
        </ul>
        <button @click="startRaffle" class="raffle-button">开始抽奖</button>
      </div>
      <div v-else>
        <h3>没有学生数据</h3>
      </div>
    </div>
  </div>
</template>

<script>
import NavigationComponent from "./NavigationComponent.vue";
import axios from "axios";
import { mapState } from "vuex";
import "@/assets/RaffleComponent.css";

export default {
  name: "RaffleComponent",
  components: {
    NavigationComponent,
  },
  data() {
    return {
      class_name: "",
      students: [],
      selectedStudentIndex: -1,
      intervalId: null,
      intervalTime: 50, // 初始间隔时间
      stopTime: 0, // 抽奖停止时间
      startTime: 0 // 抽奖开始时间
    };
  },
  computed: {
    ...mapState(["selectedDate", "selectedClass"]),
  },
  watch: {
    selectedDate(newDate) {
      console.log("selectedDate 变化:", newDate);
      this.loadStudentData();
    },
    selectedClass(newClass) {
      console.log("selectedClass 变化:", newClass);
      this.class_name = newClass;
      this.loadStudentData();
    },
  },
  mounted() {
    console.log("组件挂载，加载数据");
    this.loadStudentData();
  },
  methods: {
    loadStudentData() {
      if (!this.selectedClass) {
        console.log("没有选定班级");
        return;
      }

      console.log("加载学生数据，班级:", this.selectedClass);

      axios
        .get("/zuowei.json")
        .then((res) => {
          if (res.status === 200) {
            console.log("数据加载成功:", res.data);
            const classData = res.data.find((item) => item.className === this.selectedClass);
            if (classData) {
              this.students = classData.position.map((student) => {
                const name = Object.values(student)[0];
                const image = student.image;
                return { name, image };
              });
              console.log("学生数据加载成功:", this.students);
            } else {
              this.students = [];
              console.log("没有找到匹配的班级数据");
            }
          }
        })
        .catch((error) => {
          console.error("Axios请求失败", error);
        });
    },
    startRaffle() {
      if (this.intervalId) return; // 防止多次点击

      this.selectedStudentIndex = -1;
      this.intervalTime = 50; // 重置间隔时间
      this.startTime = Date.now();
      this.stopTime = this.startTime + Math.floor(Math.random() * 6000) + 5000; // 随机5到10秒停止

      const updateRaffle = () => {
        this.selectedStudentIndex = (this.selectedStudentIndex + 1) % this.students.length;

        const currentTime = Date.now();
        if (currentTime >= this.stopTime) {
          clearTimeout(this.intervalId);
          this.intervalId = null;
          return;
        }

        // 动态调整抽奖速度，随着时间增加而减慢
        const elapsedTime = currentTime - this.startTime;
        this.intervalTime = 50 + Math.floor(elapsedTime / 10);

        this.intervalId = setTimeout(updateRaffle, this.intervalTime);
      };

      this.intervalId = setTimeout(updateRaffle, this.intervalTime);
    }
  },
};
</script>